import axios from 'axios'


const baseURL = process.env.BASE_API
const timeout = 10000

axios.interceptors.request.use(config => {
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
})


// request拦截器
// axios.interceptors.request.use(config => {
//   if (store.getters.token) {
//     config.headers['X-Token'] = store.getters.token// 让每个请求携带自定义token 请根据实际情况自行修改
//   }
//   return config
// }, error => {
//   Message({
//     message: res.message,
//     type: 'error',
//     duration: 5 * 1000
//   })
//   Promise.reject(error)
// })

export default {
  post(url, data, header) {
    const headers = header || {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    return axios({
      method: 'post',
      baseURL,
      url,
      data,
      timeout,
      headers
    }).then((response) => {
      return checkStatus(response)
    }).then((res) => {
      return checkCode(res)
    })
  },
  get(url, params, header) {
    const headers = header || {
      'X-Requested-With': 'XMLHttpRequest'
    }
    return axios({
      method: 'get',
      baseURL,
      url,
      params,
      timeout,
      headers
    }).then((response) => {
      return checkStatus(response)
    }
    ).then((res) => {
      return checkCode(res)
    }
    )
  },
  delete(url, params, header) {
    const headers = header || {}
    return axios({
      method: 'delete',
      baseURL,
      url,
      params,
      timeout,
      headers
    }).then((response) => {
      return checkStatus(response)
    }
    ).then((res) => {
      return checkCode(res)
    })
  },
  put(url, params, header) {
    const headers = header || {}
    return axios({
      method: 'put',
      baseURL,
      url,
      params,
      timeout,
      headers
    }).then((response) => {
      return checkStatus(response)
    }
    ).then((res) => {
      return checkCode(res)
    })
  }
}

// 如果http状态码正常，则直接返回数据
function checkStatus(response) {
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    return response
    // 如果不需要除了data之外的数据，可以直接 return response.data
  }
  // 异常状态下，把错误信息返回去
  return {
    status: -404,
    msg: '网络异常'
  }
}


// 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
function checkCode(res) {
  if (res.status === -404) {
    alert(res.msg)
  }

  // 返回数据
  if (res.data && res.data.status === 10000) {
    return res.data.data
  }
}